package com.qf.service.impl;

import com.qf.dao.OrderDao;
import com.qf.dao.OrderDetailDao;
import com.qf.dao.impl.OrderDaoImpl;
import com.qf.dao.impl.OrderDetailDaoImpl;
import com.qf.pojo.Cart;
import com.qf.pojo.Order;
import com.qf.pojo.OrderDetail;
import com.qf.service.CartService;
import com.qf.service.OrderService;
import com.qf.utils.RandomUtils;
import com.qf.utils.TxUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class OrderServiceImpl implements OrderService {

    CartService cartService = new CartServiceImpl();

    OrderDao orderDao = new OrderDaoImpl();
    OrderDetailDao orderDetailDao = new OrderDetailDaoImpl();

    /**
     * 添加订单
     *  1. 生成一条订单记录
     *  2. 添加订单详情
     *  3. 删除购物车记录
     *
     * @param uid
     * @param aid
     * @return
     */
    @Override
    public Order addOrder(int uid, String aid) {
        Connection conn = TxUtils.getConn();
        try {
            conn.setAutoCommit(false);
            //获取该用户的购物车信息

            List<Cart> carts = cartService.findCartByUId(uid);
            double sum = 0;
            //求订单总额
            for (Cart cart : carts) {
                sum += cart.getMoney();
            }

            Order order = new Order();
            //设置订单id
            order.setId(RandomUtils.createActive());
            order.setUid(uid);
            //订单总额
            order.setMoney(sum);
            order.setStatus("未支付");
            order.setTime(new Date());
            order.setAid(Integer.parseInt(aid));

            orderDao.insert(order);

            //添加订单详情信息
            //一个购物车商品 对应一个订单详情
            for (Cart cart : carts) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOid(order.getId());
                orderDetail.setPid(cart.getPid());
                orderDetail.setNum(cart.getNum());
                orderDetail.setMoney(cart.getMoney());

                orderDetailDao.insert(orderDetail);
            }
            //删除购物车记录
            cartService.clearCart(uid);


            conn.commit();
            return order;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

            System.out.println("添加订单失败");
        } finally {
            try {
                TxUtils.remove();
                conn.setAutoCommit(true);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    public void paySuccess(Order order) {
        orderDao.paySuccess(order);
    }
}
